<template>
  <div class="container">
    <div class="left-partial">
      <font class="center">个人信息</font>
      <div class="item">
        <img
          :src="user.headImgUrl ? baseImgurl + user.headImgUrl : defaultHeadImg"
          class="head center"
        />
      </div>
      <div class="item">昵称：{{ user.nickName }}</div>
      <div class="item">居住地：{{ user.location }}</div>
      <div class="item">电话：{{ user.mobile }}</div>
      <div class="item center">
        <div
          class="custom-btn"
          @click="
            editorformShow = true;
            editorform = user;
          "
        >
          个人信息修改
        </div>
      </div>
      <div class="item center">
        <div class="custom-btn" @click="passwordFormShow = true">密码修改</div>
      </div>
      <div class="item center">
        <div class="custom-btn" @click="suggestFormShow = true">提建议</div>
      </div>
    </div>

    <div class="right-partial">
      <div class="partial-title">借阅信息</div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed prop="id" label="ID"> </el-table-column>
        <el-table-column prop="name" label="书名"> </el-table-column>
        <el-table-column prop="lendedDate" label="出借时间">
          <template slot-scope="scope">
            {{
              scope.row.lendedDate
                .replace("T", " ")
                .replace("Z", " ")
                .substring(0, 10)
            }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="应归时间">
          <template slot-scope="scope">
            {{
              scope.row.returnDate
                .replace("T", " ")
                .replace("Z", " ")
                .substring(0, 10)
            }}
          </template>
        </el-table-column>
        <el-table-column prop="actualReturnDate" label="是否归还">
          <template slot-scope="scope">
            {{ scope.row.actualReturnDate ? "是" : "否" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              @click="handleContinue(scope.row)"
              type="primary"
              size="small"
              :disabled="scope.row.actualReturnDate ? true : false"
              >续期</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleCalculate(scope.row)"
              :disabled="scope.row.actualReturnDate ? true : false"
              >模拟归还</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size="pageSize"
        :current-page.sync="pageNo"
        :total="total"
        layout="prev, pager, next"
        style="right: 2.5vw; position: absolute; margin-top: 1.5vw"
      >
      </el-pagination>
    </div>
    <el-dialog title="续租" :visible.sync="continueFormShow">
      <el-form
        :model="continueForm"
        :rules="rules"
        ref="continueForm"
        label-position="left"
      >
        <el-form-item
          label="续租天数"
          :label-width="defaultLabelWidth"
          prop="day"
          maxlength="20"
        >
          <el-radio-group v-model="continueForm.day">
            <el-radio label="3"></el-radio>
            <el-radio label="5"></el-radio>
            <el-radio label="7"></el-radio>
            <el-radio label="15"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('continueForm')">取 消</el-button>
        <el-button type="primary" @click="confirmContinue()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="租金计算" :visible.sync="calculateFormShow">
      <el-radio-group
        v-model="calculateForm.broken"
        @change="handleCalculate()"
      >
        <el-radio :label="0">未损坏</el-radio>
        <el-radio :label="1">损坏</el-radio>
      </el-radio-group>
      <el-descriptions
        :column="2"
        border
        class="description"
        style="margin-top: 1.5vw"
      >
        <el-descriptions-item label="ID">{{
          calculateForm.id
        }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          calculateForm.nickName
        }}</el-descriptions-item>
        <el-descriptions-item label="书名">{{
          calculateForm.name
        }}</el-descriptions-item>
        <el-descriptions-item label="借出时间">{{
          calculateForm.lendedDate
            .replace("T", " ")
            .replace("Z", " ")
            .substring(0, 19)
        }}</el-descriptions-item>
        <el-descriptions-item label="应还时间">{{
          calculateForm.returnDate
            .replace("T", " ")
            .replace("Z", " ")
            .substring(0, 19)
        }}</el-descriptions-item>

        <el-descriptions-item label="应付金额">{{
          calculateForm.pay
        }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('')">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="密码修改" :visible.sync="passwordFormShow">
      <el-form
        :model="passwordForm"
        :rules="rules"
        ref="passwordForm"
        label-position="left"
      >
        <el-form-item
          label="老密码"
          :label-width="defaultLabelWidth"
          prop="oldPassword"
          maxlength="20"
        >
          <el-input
            v-model="passwordForm.oldPassword"
            autocomplete="off"
            type="password"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="新密码"
          :label-width="defaultLabelWidth"
          prop="newPassword"
          maxlength="20"
        >
          <el-input
            v-model="passwordForm.newPassword"
            autocomplete="off"
            type="password"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('passwordForm')">取 消</el-button>
        <el-button type="primary" @click="confirmChange()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="个人信息修改" :visible.sync="editorformShow">
      <el-form
        :model="editorform"
        :rules="rules"
        ref="editorform"
        label-position="left"
      >
        <el-form-item label="头像" :label-width="defaultLabelWidth">
          <el-upload
            :action="''"
            :before-upload="imgUpload"
            :show-file-list="false"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png, .gif"
          >
            <img
              v-if="editorform.headImgUrl"
              :src="baseImgurl + editorform.headImgUrl"
              class="head"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item
          label="昵称"
          :label-width="defaultLabelWidth"
          maxlength="20"
        >
          <el-input
            v-model="editorform.nickName"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="defaultLabelWidth"
          prop="mobile"
          maxlength="20"
        >
          <el-input
            v-model="editorform.mobile"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          :label-width="defaultLabelWidth"
          prop="email"
          maxlength="50"
        >
          <el-input
            v-model="editorform.email"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="身份证号"
          :label-width="defaultLabelWidth"
          prop="idCard"
          maxlength="20"
        >
          <el-input
            v-model="editorform.idCard"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="居住地"
          :label-width="defaultLabelWidth"
          maxlength="50"
        >
          <el-input
            v-model="editorform.location"
            autocomplete="off"
            style="width: 15vw"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('editorform')">取 消</el-button>
        <el-button type="primary" @click="confirmEditor">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提建议" :visible.sync="suggestFormShow">
      <el-form
        :model="suggestForm"
        :rules="rules"
        ref="suggestForm"
        label-position="left"
      >
        <el-form-item
          label="建议内容"
          :label-width="defaultLabelWidth"
          prop="content"
          maxlength="20"
        >
          <el-input
            v-model="suggestForm.content"
            type="textarea"
            autocomplete="off"
            style="width: 100%"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle('suggestForm')">取 消</el-button>
        <el-button type="primary" @click="handleAdd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
</style>

<script>
export default {
  data() {
    let baseImgurl = window.location.origin;
    let defaultHeadImg = baseImgurl + "/public/default_user.jpeg";
    return {
      baseImgurl,
      defaultHeadImg,
      total: 0,
      pageNo: 1,
      pageSize: 8,
      continueFormShow: false,
      calculateFormShow: false,
      passwordFormShow: false,
      editorformShow: false,
      suggestFormShow: false,
      select: "idCard",
      searchField: "",
      defaultLabelWidth: "6vw",
      tableData: [],
      user: {},
      continueForm: {
        id: "",
        userId: "",
        bookId: "",
        day: "3",
      },
      calculateForm: {
        id: "",
        userId: "",
        bookId: "",
        broken: 0,
        lendedDate: "",
        returnDate: "",
        pay: 0,
      },
      editorform: {
        id: "",
        nickName: "",
        headImgUrl: "",
        location: "",
        idCard: "",
        mobile: "",
        email: "",
      },
      passwordForm: {
        oldPassword: "",
        newPassword: "",
      },
      suggestForm: {
        content: "",
      },
      rules: {
        oldPassword: [
          {
            required: true,
            message: "老密码不能为空！",
            trigger: "blur",
          },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: "新密码不能为空！",
            trigger: "blur",
          },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机号码不能为空！",
            trigger: "blur",
          },
          { validator: this.$validator.mobile, trigger: "blur" },
        ],
        content: [
          {
            required: true,
            message: "建议内容不能为空！",
            trigger: "blur",
          },
          {
            max: 200,
            message: "最长 200 个字符",
            trigger: "blur",
          },
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空！",
            trigger: "blur",
          },
          { validator: this.$validator.idCard, trigger: "blur" },
        ],
        email: [{ validator: this.$validator.email, trigger: "blur" }],
      },
    };
  },
  methods: {
    imgUpload(file) {
      let message = this.$message;
      const isIMAGE = file.type === "image/jpeg" || "image/gif" || "image/png";
      const isLt800K = file.size / 1024 < 1024;

      if (!isIMAGE) {
        message.error("上传文件只能是图片格式!");
        return false;
      }
      if (!isLt800K) {
        message.error("上传文件大小不能超过 1M!");
        return false;
      }
      if (isIMAGE && isLt800K) {
        var formdata = new FormData();
        formdata.append("file", file);
        let that = this;
        this.$axios
          .post("/api/v1/upload", formdata)
          .then((res) => {
            that.editorform.headImgUrl = res.url;
          })
          .catch((e) => {
            message.error(e.data.message);
          });
      }
      return false;
    },
    getUserInfo() {
      let that = this;
      this.$axios.get("/api/v1/user/info").then((data) => {
        that.user = data;
      });
    },
    getList() {
      let that = this;
      let query = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
      };
      query.role = this.role;
      query[this.select] = this.searchField;
      let queryStr = this.$query.stringify(query);
      this.$axios.get(`/api/v1/lend_infos?${queryStr}`).then((data) => {
        that.total = data.totalCount;
        that.pageNo = data.pageNo;
        that.tableData = data.infos;
      });
    },
    handleAdd() {
      let that = this;
      this.$refs["suggestForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .post("/api/v1/suggest", this.suggestForm)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "操作成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                this.$refs["suggestForm"].resetFields();
                this.suggestFormShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
    handleContinue(row) {
      this.continueForm = row;
      this.continueFormShow = true;
    },
    handleCalculate(row) {
      if (row) {
        this.calculateForm = row;
      }
      let that = this;
      let id = this.calculateForm.id;
      let broken = this.calculateForm.broken;
      this.$axios
        .get(`/api/v1/lend_info/calculate?id=${id}&broken=${broken ? 1 : 0}`)
        .then((data) => {
          that.$set(that.calculateForm, "pay", data.pay);
          that.calculateFormShow = true;
        });
    },
    cancle(formName) {
      if (formName) {
        this.$refs[formName].resetFields();
      }
      if (formName == "editorform") {
        this.getUserInfo();
      }
      this.continueFormShow = false;
      this.calculateFormShow = false;
      this.editorformShow = false;
      this.passwordFormShow = false;
      this.suggestFormShow = false;
    },
    confirmContinue() {
      let that = this;
      this.$refs["continueForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/api/v1/lend_info", this.continueForm)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "操作成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                this.$refs["continueForm"].resetFields();
                that.getList();
                that.continueFormShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
    confirmChange() {
      let that = this;
      this.$refs["passwordForm"].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/api/v1/user/change_password", this.passwordForm)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "修改成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                that.$refs["passwordForm"].resetFields();
                that.passwordFormShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
    confirmEditor() {
      let that = this;
      this.$refs["editorform"].validate((valid) => {
        if (valid) {
          this.$axios
            .put("/api/v1/user", this.editorform)
            .then((data) => {
              if (data.result) {
                that.$message.success({
                  message: "修改成功",
                  center: true,
                  offset: screen.availHeight * 0.32,
                  duration: 1200,
                });
                that.$refs["editorform"].resetFields();
                that.getUserInfo();
                that.editorformShow = false;
              }
            })
            .catch((err) => {
              that.$message.error({
                message: err.data.message,
                center: true,
                offset: screen.availHeight * 0.32,
                duration: 1200,
              });
            });
        }
      });
    },
  },
  beforeMount() {
    this.$axios.post("/api/v1/user/verified");
    this.getUserInfo();
    this.getList();
  },
};
</script>
